import { useStreams } from '@/lib/utils'
import services from '@/services'
import { ContactType } from '@/services/contacts'

export function useUnreadOfTypes() {
  const [metaUnreads, mutes] = useStreams(services.chat.metas.unreads, services.groups.mutes)

  const unreads = useMemo(() => {
    const initial = {
      [ContactType.external]: 0,
      [ContactType.group]: 0,
      [ContactType.internal]: 0,
    }
    return metaUnreads.reduce((unreads, item) => {
      if (item.type === ContactType.external) {
        unreads[ContactType.external] += item.unread
      } else if (item.type === ContactType.internal || item.type === ContactType.notice) {
        unreads[ContactType.internal] += item.unread
      } else if (item.type === ContactType.group && !mutes.has(item.contactId)) {
        // 对于群，只统计未“静音”的群的未读消息数
        unreads[ContactType.group] += item.unread
      }
      return unreads
    }, initial)
  }, [metaUnreads, mutes])

  return unreads
}
